<template>
  <div class="list">
    <van-nav-bar
      title="购物车"
      left-text="返回"
      right-text="首页"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    />
    <van-swipe-cell v-for="item in carts" :key="item.id">
      <van-card
        :num="item.amount"
        :price="item.product.price.toFixed(2)"
        :title="item.product.name"
        :thumb="item.product.coverImage | dalImg"
        @click="onClickDetail(item.product.id)"
      >
        <template #tag>
          <van-checkbox v-model="item.chk"></van-checkbox>
        </template>
        <template #footer>
          <van-stepper
            v-model="item.amount"
            @plus="addToCart(item, 1)"
            @minus="addToCart(item, -1)"
          ></van-stepper>
        </template>
      </van-card>
      <template #right>
        <van-button square text="删除" @click="del(item.id)" type="danger" class="delete-button" />
      </template>
    </van-swipe-cell>
    <van-submit-bar :price="sumPrice" button-text="提交订单" @submit="onSubmit">
      <van-checkbox v-model="checkAll">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import { addToCartAPI, loadCartAPI, delFromCartByIdAPI } from '../services/carts';
export default {
  data() {
    return {
      checked: true,
      // amount: 1,
      carts: [],
    };
  },

  async created() {
    const res = await loadCartAPI();
    // console.log(res);
    this.carts = res.data.filter((item) => item.product).map((item) => ({ ...item, chk: false }));
  },
  methods: {
    onSubmit() {},
    onClickLeft() {
      this.$router.go(-1);
    },
    onClickRight() {
      this.$router.push({
        name: 'Home',
      });
    },
    onClickDetail(id) {
      if (event.target.classList.contains('van-image__img')) {
        this.$router.push({
          name: 'Detail',
          query: {
            id,
          },
        });
      }
    },
    async addToCart(item, amount) {
      await addToCartAPI({
        product: item.product.id, //商品id
        amount, //数量，-1表示减，1表示加
        price: item.product.price,
      });
    },
    async del(id) {
      await delFromCartByIdAPI(id);
      this.carts.splice(
        this.carts.findIndex((item) => item.id === id),
        1
      );
    },
  },
  computed: {
    checkAll: {
      set(v) {
        this.carts.forEach((item) => {
          item.chk = v;
        });
      },
      get() {
        return this.carts.length > 0 ? this.carts.every((item) => item.chk) : false;
      },
    },
    sumPrice() {
      return (
        this.carts
          .filter((item) => item.chk)
          .reduce((pre, cur) => pre + cur.amount * cur.product.price, 0) * 100
      );
    },
  },
};
</script>

<style scoped>
.delete-button {
  height: 100%;
}
</style>
